package com.lxx.securitydemo2.service.impl;


import com.lxx.securitydemo2.config.JwtProperties;
import com.lxx.securitydemo2.constants.JwtClaimsConstant;
import com.lxx.securitydemo2.domain.entity.LoginUser;
import com.lxx.securitydemo2.domain.ResponseResult;
import com.lxx.securitydemo2.domain.vo.LoginVo;
import com.lxx.securitydemo2.service.LoginService;
import com.lxx.securitydemo2.utils.JwtUtils;
import com.lxx.securitydemo2.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;


    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisUtil redisUtil;


    @Override
    public ResponseResult login(LoginVo loginVo) {
        // Authentication接口: 它的实现类，表示当前访问系统的用户，封装了用户相关信息。
        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(loginVo.getUserName(), loginVo.getPassword());
        // AuthenticationManager接口：定义了认证Authentication的方法
        Authentication authenticate = authenticationManager.authenticate(authentication);
        //如果认证没有通过，给出响应提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        //如果认证通过了，使用userid生成一个jwt jwt存入ResponseResult返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();

        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, userId);
        String jwt = JwtUtils.createJwt(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims
        );

        //把完整的用户信息存入redis  userid作为key
        redisUtil.set("login:" + userId, loginUser);

        //把token响应给前端
        HashMap<String, String> map = new HashMap<>();
        map.put("token", jwt);
        return new ResponseResult(200, "登录成功", map);
    }

    @Override
    public ResponseResult logout() {
        //获取SecurityContextHolder中得用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId = String.valueOf(loginUser.getUser().getId());
        //删除redis中的值
        String redisKey = "login:" + userId;
        redisUtil.del(redisKey);
        return new ResponseResult(200, "退出成功");
    }

}

